package com.ccys.netty.handler;

import io.grpc.netty.shaded.io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author 心跳检测处理
 * @description 描述
 * @date 2024/3/2
 */
public class MyIdleStateHandler extends ChannelDuplexHandler {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                // 连接超时，关闭连接
                ctx.close();
            } else if (state == IdleState.WRITER_IDLE) {
                // 发送心跳消息
                ctx.writeAndFlush(new TextWebSocketFrame("ping"));
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
